package com.momo.mal.anime.view;

import org.json.JSONException;
import org.json.JSONObject;

import net.momo.mal.R;
import com.momo.mal.database.MalDatabaseAdapter;
import com.momo.mal.entity.Anime;
import com.momo.mal.util.AnimeUtil;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class AnimeTabSynopsys extends Fragment {
	private JSONObject jsonObject;
	private String mContent = "???";
	
	private static final String KEY_CONTENT = "AnimeTabSynopsis:Content";
	
	public static AnimeTabSynopsys newInstance(JSONObject jsonObject) {
		AnimeTabSynopsys fragment = new AnimeTabSynopsys();
		fragment.jsonObject = jsonObject;
		
		return fragment;
	}
	

	@Override
	public void onPause() {
		super.onPause();
		getActivity().getIntent().putExtra("json", jsonObject.toString());
	}
	
	@Override
	public void onResume() {
		super.onResume();
		if(getActivity().getIntent().hasExtra("json")) {
			try {
				jsonObject = new JSONObject(getActivity().getIntent().getStringExtra("json"));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		if(getActivity().getIntent().hasExtra("json")) {
			try {
				jsonObject = new JSONObject(getActivity().getIntent().getStringExtra("json"));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		
		if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
            mContent = savedInstanceState.getString(KEY_CONTENT);
        }
	}
		
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.anime_view_synopsys, null);
		MalDatabaseAdapter dbAdapter = new MalDatabaseAdapter(getActivity());
		
		TextView synopsys = (TextView) view.findViewById(R.id.text_synopsis);
		Anime anime = new Anime();
		try {
			JSONObject json = jsonObject;
			if(json.has("sync") == true) {
				anime = dbAdapter.getAnimeById(json.getString("anime_id"));
			} else {
				anime = AnimeUtil.parsingAnimeFromJson(json);
			}
			synopsys.setText(Html.fromHtml(anime.getSynopsis() + ""));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		return view;
	}
}
